<?php
/**
 * User: krisbuist
 * Date: 1/31/12
 * Time: 9:33 PM
 */
class CommentGenerator extends Controller
{
    protected $step = 500;

    protected $numberOfAuthors;
    protected $numberOfPosts;

    protected $avgNumberOfCommentsPerPost = 3;
    protected $totalNumberOfComments;

    protected $minCommentLength = 10;
    protected $maxCommentLength = 50;

    public function __construct()
    {
        parent::__construct();
        $this->load->library('/generators/RandomTextGenerator');
        $this->numberOfAuthors = $this->em->createQuery("SELECT COUNT(u) FROM User u")->getSingleScalarResult();
        $this->numberOfPosts = $this->em->createQuery("SELECT COUNT(p) FROM Post p")->getSingleScalarResult();
        $this->totalNumberOfComments = $this->numberOfPosts * $this->avgNumberOfCommentsPerPost;
    }

    public function generateComments()
    {
        try
        {
            for ($i = 0; $i < $this->step; $i++)
            {
                $post = $this->em->find('Post', rand(1,$this->numberOfPosts));
                $comment = $this->generateRandomComment($post);
                $this->em->persist($comment);
            }

            $this->em->flush();
        }
        catch (PDOException $e)
        {
            echo $e;
        }


        $this->forwardBrowserIfNotFinished();
    }

    public function forwardBrowserIfNotFinished()
    {
        $numberOfComments = $this->em->createQuery("SELECT COUNT(c) FROM Comment c")->getSingleScalarResult();
        if ($numberOfComments >= $this->totalNumberOfComments)
        {
            echo 'Finished inserting comments!';
        }
        else
        {
            echo '<meta http-equiv="refresh" content="0;url=/generators/commentGenerator/generateComments">';
            echo '<title>' . $numberOfComments .'</title>';
        }
    }

    private function generateRandomComment($post)
    {
        $comment = new Comment();
        $comment->setAuthor($this->getRandomAuthor());
        $comment->setPost($post);
        $comment->setCommentText($this->randomtextgenerator->getContent(rand($this->minCommentLength,$this->maxCommentLength), 'plain', false));
        return $comment;
    }

    /**
     * @return User
     */
    private function getRandomAuthor()
    {
        $author = null;
        while ($author == null)
        {
            $author = $this->em->find('User', rand(1, $this->numberOfAuthors));
        }
        return $author;
    }

}
